package bid.yanhj.springboot.task;

import java.util.Random;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import groovy.util.logging.Slf4j;

/**
 * 
 * @author yanhaijiang 注： @Async所修饰的函数不要定义为static类型，这样异步调用不会生效.
 */
@Slf4j
@Component
public class Task {

    /**
     * LOG.
     */
    private static final Logger LOG = LoggerFactory.getLogger(Task.class);

    public static Random random = new Random();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Async("taskExecutor")
    public Future<String> doTaskOne() throws Exception {
        LOG.info("开始做任务一");
        long start = System.currentTimeMillis();

//        LOG.info(stringRedisTemplate.randomKey());

        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        LOG.info("完成任务一，耗时：" + (end - start) + "毫秒");
        return new AsyncResult<>("任务一完成");
    }

    @Async("taskExecutor")
    public Future<String> doTaskTwo() throws Exception {
        LOG.info("开始做任务二");
        long start = System.currentTimeMillis();

//        LOG.info(stringRedisTemplate.randomKey());

        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        LOG.info("完成任务二，耗时：" + (end - start) + "毫秒");
        return new AsyncResult<>("任务二完成");
    }

    @Async("taskExecutor")
    public Future<String> doTaskThree() throws Exception {
        LOG.info("开始做任务三");
        long start = System.currentTimeMillis();

//        LOG.info(stringRedisTemplate.randomKey());

        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        LOG.info("完成任务三，耗时：" + (end - start) + "毫秒");
        return new AsyncResult<>("任务三完成");
    }
    
    @Async("taskExecutor")
    public Future<String> run() throws Exception {
        long sleep = random.nextInt(10000);
        LOG.info("开始任务，需耗时：" + sleep + "毫秒");
        Thread.sleep(sleep);
        LOG.info("完成任务");
        return new AsyncResult<>("test");
    }
}
